<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="box1"></div>
    <div id="box2"></div>
    <script>

        var box1 = document.getElementById('box1')
        var box2 = document.getElementById('box2')

        drag(box1)
        drag(box2)

        // 封装
        function drag(obj) {
            //绑定按下事件
            obj.onmousedown = function (event) {
                //捕获 浏览器兼容
                if (obj.setCapture) {
                    obj.setCapture();//只有ie支持

                }
                event = event || window.event
                //求出偏移量 鼠标。clentX-元素。offsetLift
                var oleft = event.clientX - obj.offsetLeft
                //求出偏移量 鼠标。clentY-元素。offsetTop
                var otop = event.clientY - obj.offsetTop


                //鼠标移动绑定onmousemove
                //给document绑定移动事件
                document.onmousemove = function (event) {
                    //获取坐标位置
                    event = event || window.event
                    var left = event.clientX - oleft;
                    var top = event.clientY - otop;

                    //修改box1的位置
                    obj.style.left = left + "px";
                    obj.style.top = top + "px";
                }
                // 取消浏览器的默认行为  ie8 不起作用
                return false
            }
            //鼠标松开事件onmouseup
            document.onmouseup = function () {
                //取消onmousemove事件
                document.onmousemove = null;
                //取消onmousemove事件
                // document.onmouseup = null;
                //当取消时，取消事件捕获
                if (obj.releaseCapture) {
                    obj.releaseCapture();//只有ie支持

                }

            }
        }



    </script>
</body>
<style>
    #box1 {
        height: 100px;
        width: 100px;
        background-color: red;
        position: absolute;
    }

    #box2 {
        height: 100px;
        width: 100px;
        background-color: rgb(17, 0, 255);
        position: absolute;
        top: 200px;
    }
</style>

</html>